package com.zbcz.crm.fragment.marketmanager

import InvitedBeanListFragment.Companion.getFileNameFromPath
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.zbcz.crm.MarketManagerActivity
import com.zbcz.crm.adapter.AuditBeanListAdapter
import com.zbcz.crm.databinding.FragmentCommonListBinding
import com.zbcz.crm.fragment.marketmanager.TenderFragment.Companion.REQUEST_PERMISSION_CODE
import com.zbcz.crm.network.RetrofitManager
import com.zbcz.crm.util.ToastUtils
import com.zbcz.crm.viewmodel.AuditBeanViewModel
import com.zbcz.crm.viewmodel.MarketManagerViewModel
import kotlinx.coroutines.launch

class AuditBeanFragment : Fragment() {

    private lateinit var binding: FragmentCommonListBinding

    private val mViewModel: AuditBeanViewModel by viewModels()

    private val mMarketMangerViewModel: MarketManagerViewModel by activityViewModels()

    companion object {
        const val TAG = "AuditBeanFragment"

        fun createAuditFragment(id: String): AuditBeanFragment {
            return AuditBeanFragment().apply {
                val args = Bundle()
                args.putString(MarketManagerActivity.PROJECT_ID, id)
                arguments = args
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentCommonListBinding.inflate(inflater, container, false)
        init()
        return binding.root
    }

    fun init() {
        val id = arguments?.getString(MarketManagerActivity.PROJECT_ID)
        mViewModel.queryAudit(id)
        mViewModel.mResult.observe(requireActivity()) {
            binding.mList.adapter = it?.let { it1 ->
                AuditBeanListAdapter(it1).apply {
                    onItemFileClickListener = { position, filePath ->
                        checkAndRequestPermissions { granted ->
                            if (granted) {
                                downloadFile(filePath)
                            } else {
                                // 权限被拒绝，可以给出提示或者处理相应逻辑
                            }
                        }
                    }
                }
            }
        }
    }

    private var permissionCallback: ((granted: Boolean) -> Unit)? = null
    private fun downloadFile(filePath: String) {
        lifecycleScope.launch {
            val uri = mMarketMangerViewModel.downloadFile(
                requireContext(),
                RetrofitManager.getImageUrl(filePath),
                getFileNameFromPath(filePath)
            )
            uri?.let {
                Log.i(TAG, it.toString())
                // 在此处处理文件Uri，例如打开文件、共享文件等
                ToastUtils.show("保存成功在 " + uri.path)
            }
        }
    }

    private fun checkAndRequestPermissions(callback: (granted: Boolean) -> Unit) {
        if (ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            permissionCallback = callback
            requestPermissions(
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                REQUEST_PERMISSION_CODE
            )
        } else {
            callback(true)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_PERMISSION_CODE) {
            val granted =
                grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED
            permissionCallback?.invoke(granted)
            permissionCallback = null
        }
    }
}